package com.appsino.bingluo.secret;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.appsino.bingluo.secret.Utils.Utils;
import com.scottyab.aescrypt.AESCrypt;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;

import androidx.core.app.NotificationCompat;

public class ClipyService extends Service {

    private static WindowManager iconwm;

    private static WindowManager.LayoutParams iconparams;

    private ImageView iv_show_pop;

    private View iconfloatView;

    private float iconstartX = 0;

    private float iconstartY = 0;

    private float iconx;

    private float icony;
    /**
     * 第二主弹窗
     */
    private static WindowManager.LayoutParams params;

    private View floatView;

    private float startX = 0;

    private float startY = 0;

    private float x;

    private float y;

    private int count = 0;

    private boolean F_WINDOW = false;
    private boolean S_WINDOW = false;
    private EditText titleText;
    private Button jiami;
    private String CopyString ="";
    private boolean APPCOPY = false;
    private final static String DIVIDE_RESULT = "com.intel.unit.Clipy";
    private boolean stop_state = true;
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("onBind----");
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("onUnbind----");
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("onCreate----");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            setForegroundService();
        }
        createFloatView();
        final ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        cm.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
            @Override
            public void onPrimaryClipChanged() {
                Log.i("tag","===========舰艇剪贴板内容"+F_WINDOW+"   "+S_WINDOW);
                if(APPCOPY == false){
                    ClipData data = cm.getPrimaryClip();
                    ClipData.Item item = data.getItemAt(0);
                    CopyString = item.getText().toString();
                    if(F_WINDOW==true&&floatView==null){
                        createMainFloatView();
                    }else if(F_WINDOW==true&floatView!=null){
                        creatSwindow();
                        titleText.setText(item.getText().toString());
                        jiami.performClick();
                    }else{
                        titleText.setText(item.getText().toString());
                    }
                }else{
                    APPCOPY = false;
                }
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand----");
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 创建悬浮窗
     */
    private void createFloatView() {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        iconfloatView = layoutInflater.inflate(R.layout.show_popup_window, null);
        iconwm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        iconparams = new WindowManager.LayoutParams();
        // 设置window type
        if (Build.VERSION.SDK_INT >= 26) {
            iconparams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else if (Build.VERSION.SDK_INT >= 24) { /*android7.0不能用TYPE_TOAST*/
            iconparams.type = WindowManager.LayoutParams.TYPE_PHONE;
        } else {   /*以下代码块使得android6.0之后的用户不必再去手动开启悬浮窗权限*/
            iconparams.type = WindowManager.LayoutParams.TYPE_TOAST;
        }
        iconparams.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        // 设置Window flag
        iconparams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // 设置悬浮窗的长得宽
        iconparams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        iconparams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        iconparams.gravity = Gravity.LEFT | Gravity.TOP;
        iconparams.x = 0;
        iconparams.y = 0;
        // 设置悬浮窗的Touch监听
        iconfloatView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                iconx = event.getRawX();
                icony = event.getRawY();
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        iconstartX = event.getX();
                        iconstartY = event.getY();

                        break;
                    case MotionEvent.ACTION_MOVE:
                        iconparams.x = (int)( iconx - iconstartX);
                        iconparams.y = (int) (icony - iconstartY);
                        iconwm.updateViewLayout(iconfloatView, iconparams);
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i("tag","mandroid.cn原始位置xy"+iconstartX+"   "+icony);
                        Log.i("tag","mandroid.cn当前位置xy"+event.getRawX()+"   "+event.getRawY());
                        if (Math.abs(event.getX() - iconstartX) < 50 && Math.abs(event.getY() - iconstartY) < 10) {
                            Log.i("mandroid.cn", "button未移动");
                            try {
                                Field field = View.class.getDeclaredField("mListenerInfo");
                                field.setAccessible(true);
                                Object object = field.get(iconfloatView);
                                field = object.getClass().getDeclaredField("mOnClickListener");
                                field.setAccessible(true);
                                object = field.get(object);
                                if (object != null && object instanceof View.OnClickListener) {
                                    ((View.OnClickListener) object).onClick(iconfloatView);
                                }
                            } catch (Exception e) {

                            }
                        } else {
                            Log.i("mandroid.cn", "button已移动");
                        }
                        iconstartX = iconstartY = 0;
                        break;
                }
                return true;
            }
        });
        iconwm.addView(iconfloatView, iconparams);
        F_WINDOW = true;
        iv_show_pop = iconfloatView.findViewById(R.id.iv_show_pop);
        iconfloatView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                F_WINDOW = false;
                S_WINDOW = true;
                if(floatView==null){
                    createMainFloatView();
                }else{
                    iconwm.addView(floatView,params);
                    Log.i("tag","================fuzhineirong"+CopyString);
                    titleText.setText(CopyString);
                }
                iconwm.removeView(iconfloatView);
            }
        });


//        isAdded = true;
    }

    /**
     * 创建主悬浮窗
     */
    private void createMainFloatView() {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        floatView = layoutInflater.inflate(R.layout.dict_popup_window, null);
        if(iconwm==null){
            iconwm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        }
        params = new WindowManager.LayoutParams();
        // 设置window type
//        params.type = WindowManager.LayoutParams.TYPE_PHONE;
        if (Build.VERSION.SDK_INT >= 26) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else if (Build.VERSION.SDK_INT >= 24) { /*android7.0不能用TYPE_TOAST*/
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        } else {   /*以下代码块使得android6.0之后的用户不必再去手动开启悬浮窗权限*/
//            String packname = Context.getPackageName();
//            PackageManager pm = context.getPackageManager();
//            boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.SYSTEM_ALERT_WINDOW", packname));
//            if (permission) {
//                params.type = WindowManager.LayoutParams.TYPE_PHONE;
//            } else {
            params.type = WindowManager.LayoutParams.TYPE_TOAST;
//            }
        }
        /*
         * 如果设置为params.type = WindowManager.LayoutParams.TYPE_PHONE; 那么优先级会降低一些,
         * 即拉下通知栏不可见
         */
        params.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        // 设置Window flag
//        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        /*
         * 下面的flags属性的效果形同“锁定”。 悬浮窗不可触摸，不接受任何事件,同时不影响后面的事件响应。
         * wmParams.flags=LayoutParams.FLAG_NOT_TOUCH_MODAL |
         * LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCHABLE;
         */
        // 设置悬浮窗的长得宽
        DisplayMetrics dm = new DisplayMetrics();
        iconwm.getDefaultDisplay().getMetrics(dm);
        int SCREEN_WIDTH = dm.widthPixels/3*2;
        Log.i("tag","===================sdfdsf"+SCREEN_WIDTH);
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.CENTER;
        params.x = 0;
        params.y = 0;
        // 设置悬浮窗的Touch监听
        floatView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                x = event.getRawX();
                y = event.getRawY();
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getX();
                        startY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        params.x = (int)( x - startX);
                        params.y = (int) (y - startY);
                        iconwm.updateViewLayout(floatView, params);
                        break;
                    case MotionEvent.ACTION_UP:
                        startX = startY = 0;
                        break;
                }
                return true;
            }
        });
        creatSwindow();
//        isAdded = true;
        setupCellView(floatView);
    }

    /**
     * 设置浮窗view内部子控件
     * @param rootview
     */
    private void setupCellView(View rootview) {
        Button closedImg = rootview.findViewById(R.id.btn_dialog_close);
        final TextView tvresult = rootview.findViewById(R.id.tv_secret_result);
        titleText = rootview.findViewById(R.id.float_window_title);
        jiami = rootview.findViewById(R.id.btn_jiami);
        LinearLayout llbg = rootview.findViewById(R.id.ll_pp_bg);
        LinearLayout llbottom = rootview.findViewById(R.id.ll_pp_bg_bottom);
        Button btnshare = rootview.findViewById(R.id.btn_dialog_share);
        Button btnquestion = rootview.findViewById(R.id.btn_dialog_question);
        Button btncopy = rootview.findViewById(R.id.btn_copy);
        titleText.setText(CopyString);
        btnshare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {

                } catch (Exception e) {
                    Log.i("tag","======fdffdfd"+e);
                    e.printStackTrace();
                }
            }
        });
        llbottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(iconwm!=null){
                    creatFwindow();
                }
            }
        });
        llbg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(iconwm!=null){
                    creatFwindow();
                }
            }
        });
        btnquestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Intent mIntent = new Intent();
                    mIntent.setAction(ClipyToastBroadcast.Action_Name);
                    sendBroadcast(mIntent);
                    creatFwindow();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        closedImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (isAdded) {
                    titleText.setText("");
                    tvresult.setText("");
                    CopyString = "";
                    if(iconwm!=null){
                        creatFwindow();
                    }
//                    wm.removeView(floatView);
//                    isAdded = false;
//                }
            }
        });
        floatView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        //加密剪贴板内容
        jiami.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String content = titleText.getText().toString();
                    if(content.endsWith("*#*")){
                        String password = "password";
                        String messageAfterDecrypt = AESCrypt.decrypt(password, content.substring(0,content.length()-3));
                        tvresult.setText(messageAfterDecrypt);
                    }else{
                        String password = "password";
                        String encryptedMsg = AESCrypt.encrypt(password, content)+"*#*";
                        tvresult.setText(encryptedMsg);
                    }
                    //传输过程,不转成16进制的字符串，就等着程序崩溃掉吧
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        tvresult.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(!TextUtils.isEmpty(editable.toString().trim())){
                    btncopy.setBackgroundResource(R.drawable.icon_flow_copyys);
                }else{
                    btncopy.setBackgroundResource(R.drawable.icon_flow_copyno);
                }
            }
        });
        //复制文本内容到剪贴板
        btncopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    APPCOPY = true;
                    String text = tvresult.getText().toString();
                    ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("simple text", text);
                    clipboard.setPrimaryClip(clip);
                    titleText.setText("");
                    tvresult.setText("");
                    CopyString = "";
                    Utils.ToastSign(ClipyService.this,"内容已复制，可在任意区域粘贴\n");
                    creatFwindow();
                } catch (Exception e) {
                    Log.i("tag","==============舰艇剪"+e);
                    e.printStackTrace();
                }
            }
        });
        if(!TextUtils.isEmpty(CopyString)){
            jiami.performClick();
        }
    }
    @Override
    public void onDestroy() {
        System.out.println("onDestroy----");
        super.onDestroy();
        if(F_WINDOW==true){
            F_WINDOW = false;
            iconwm.removeView(iconfloatView);
        }
        if(S_WINDOW==true){
            S_WINDOW = false;
            iconwm.removeView(floatView);
        }
        System.out.println("onDestroy->account---->" + count);
//        if (stop_state) {
            this.stopSelf();
//        } else {
//            this.startService(new Intent(this, ClipyService.class));
//        }
    }

    /**
     *通过通知启动服务
     */
    @androidx.annotation.RequiresApi(api = Build.VERSION_CODES.O)
    public void  setForegroundService()
    {
        //设定的通知渠道名称
        String channelName = "测试前台服务";
        //设置通知的重要程度
        int importance = NotificationManager.IMPORTANCE_LOW;
        //构建通知渠道
        NotificationChannel channel = new NotificationChannel("1000", channelName, importance);
        channel.setDescription("cehis");
        //在创建的通知渠道上发送通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "1000");
        builder.setSmallIcon(R.mipmap.ic_launcher) //设置通知图标
                .setContentTitle("区块链加密")//设置通知标题
                .setContentText("加密服务正在运行")//设置通知内容
                .setAutoCancel(true) //用户触摸时，自动关闭
                .setOngoing(true);//设置处于运行状态
        //向系统注册通知渠道，注册后不能改变重要性以及其他通知行为
        NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
        //将服务置于启动状态 NOTIFICATION_ID指的是创建的通知的ID
        startForeground(1111111,builder.build());
    }

    public void creatFwindow(){
        F_WINDOW = true;
        S_WINDOW = false;
        iconwm.removeView(floatView);
        iconwm.addView(iconfloatView,iconparams);
    }

    public void creatSwindow(){
        F_WINDOW = false;
        S_WINDOW = true;
        iconwm.addView(floatView,params);
        iconwm.removeView(iconfloatView);
    }
}